package languageacquisition;

import java.util.logging.Logger;

import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.domain.FIPAAgentManagement.ServiceDescription;

/**
 * @author Necklon
 * Extended agent with the method to register/searching services on DF
 */
public class ProjectAgent extends Agent {
	
	
	private static final long serialVersionUID = -5901548802496758989L;
	
	protected Logger logger = Logger.getLogger("laf");
	
	/**
	 * Registers service provided by agent
	 * 
	 * @param serviceType type of service
	 */
	protected void registerService(String serviceType) {
		ServiceDescription sd = new ServiceDescription();
		sd.setType(serviceType);
		sd.setName(serviceType + "-" + getLocalName());
		// TODO: add languages, protocols and ontologies do DF description
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		dfd.addServices(sd);

		try {
			DFService.register(this, dfd);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
	}

	protected void takeDown() {
		try {
			DFService.deregister(this);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
		System.out.println(getAID().getLocalName() + " stops working");
	}

	protected AID[] searchDF(String service) {
		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(service);
		dfd.addServices(sd);

		SearchConstraints ALL = new SearchConstraints();
		ALL.setMaxResults(new Long(-1));

		try {
			DFAgentDescription[] result = DFService.search(this, dfd, ALL);
			AID[] agents = new AID[result.length];
			for (int i = 0; i < result.length; i++)
				agents[i] = result[i].getName();
			return agents;

		} catch (FIPAException fe) {
			fe.printStackTrace();
		}

		return null;
	}

}
